package com.googlecode.bluetools.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.codehaus.classworlds.uberjar.protocol.jar.JarUrlConnection;

/**
 * @author Nick.Tan
 */
public abstract class UrlUtil {

	/**
	 * Open Jar: url with <code>classworlds</code> Jar url stream handler
	 * <code>org.codehaus.classworlds.uberjar.protocol.jar.Handler</code>
	 * 
	 * It's a workaroud for <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4823678">Sun bug 4823678</a>.<br/>
	 * Yet, another workaround is to provide an alternate URLStreamHandler for the jar: protocol. But I failed to do so
	 * maybe because of tomcat classload or something else.
	 * 
	 * @param url
	 * @return the underlying <code>java.io.InputStream</code>
	 * @throws IOException
	 */
	public static InputStream openStream(URL url) throws IOException {
		if ("jar".equalsIgnoreCase(url.getProtocol())) {
			org.codehaus.classworlds.uberjar.protocol.jar.Handler jarHandler = org.codehaus.classworlds.uberjar.protocol.jar.Handler
					.getInstance();
			JarUrlConnection jarConn = (JarUrlConnection) jarHandler.openConnection(url);
			return jarConn.getInputStream();
		}
		return url.openStream();
	}
}
